//
//  ViewController.m
//  WifiDemo
//
//  Created by Advance Sound Devices ASD on 3/9/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "ViewController.h"
#import "ASIFormDataRequest.h"
#import "ASIHTTPRequest.h"
#import "SBJson.h"

@implementation ViewController
@synthesize receivedData;
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
    receivedData = [[NSMutableData dataWithLength:100000] retain];
    webView.scalesPageToFit =YES;
    webView.delegate =self;
    activityIndicatorView = [[UIActivityIndicatorView alloc] 
                             initWithFrame : CGRectMake(0.0f, 0.0f, 32.0f, 32.0f)] ;
    [activityIndicatorView setCenter: self.view.center] ;
    [activityIndicatorView setActivityIndicatorViewStyle: UIActivityIndicatorViewStyleWhite] ; 
    [self.view addSubview : activityIndicatorView] ;
}

- (IBAction)buttonPress:(id) sender
{
   //通过NSURLRequest获得服务器返回的http header和http status 
//    NSURL *url = [NSURL URLWithString:@"http://192.168.1.254/sweb/index.htm"];
//    NSURLRequest *request = [NSURLRequest requestWithURL: url];
//    NSHTTPURLResponse *response;
//    [NSURLConnection sendSynchronousRequest: request returningResponse: &response error: nil];
//    if ([response respondsToSelector:@selector(allHeaderFields)]) {
//        // 取得所有的请求的头
//        NSDictionary *dictionary = [response allHeaderFields];
//        NSLog(@"dictionary=%@",[dictionary description]);
//        // 取得http状态码
//        NSLog(@"%d",[response statusCode]);
//        
//    }
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
    NSString *text = @"d";
    NSString *key = @"sweb_console_input";
    NSString *postMsg =[NSString stringWithFormat:@"sweb_console_input=%@",text];
	//NSData *postData = [postMsg dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
    NSData *postData = [postMsg dataUsingEncoding:NSUTF8StringEncoding];
	NSString *postLength = [NSString stringWithFormat:@"%d",[postData length]];
	
	NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://192.168.1.254/sweb/index.htm?sweb_console_input=d"]];
//	[request setHTTPMethod:@"POST"];
//	[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
//	//[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
//    [request setValue:@"text/html" forHTTPHeaderField:@"Content-Type"];
//	[request setHTTPBody:postData];
    
//    NSHTTPURLResponse *response=nil;
//    NSError *error=[[NSError alloc] init];
//    NSData *responseData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
//    NSStringEncoding encoding = NSUTF8StringEncoding;
//    NSLog(@"responseData=%@",[[[NSString alloc] initWithData:responseData encoding:encoding] JSONValue]);
//    NSLog(@"response statusCode=%d",[response statusCode]);
//    if([response statusCode]>=200&&[response statusCode]<400&&[response respondsToSelector:@selector(allHeaderFields)])
//    {
//        //        NSStringEncoding encoding;
//        //        NSDictionary *headers=[response allHeaderFields];
//        //        NSString *contentType=[headers objectForKey:@"Content-Type"];
//        //        
//        //        if([[contentType lowercaseString] rangeOfString:@"gb2312"].location>0)
//        //        {
//        //            NSLog(@"kCFStringEncodingGB_18030_2000");
//        //            encoding=CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
//        //        }
//        //        else
//        //        {
//        //            NSLog(@"NSUTF8StringEncoding");
//        //            encoding=NSUTF8StringEncoding;
//        //        }
//        NSStringEncoding encoding = NSUTF8StringEncoding;
//        NSLog(@"responseData : %@",[[NSString alloc] initWithData:responseData encoding:encoding]);
//        NSLog(@"string=%@",[[[NSString alloc] initWithData:responseData encoding:encoding] JSONValue]) ;
//    }
    
	[NSURLConnection connectionWithRequest:request delegate:self];
}
//接收NSData数据

#pragma mark NSURLConnection

- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    NSString *str = [response URL];
//	UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Alert" message:@"Your words has been sent out!" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
//	[alert show];
//	[alert release];
	//[self.receivedData appendData:[response res]];
}

- (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
	NSLog(@"2");
}

- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
	//[self.receivedData appendData:data];
	NSLog(@"3");
    [receivedData appendData:data];
}

- (void) connectionDidFinishLoading:(NSURLConnection *)connection
{
	NSLog(@"4");
	

    NSString *str = [NSString stringWithCString:[receivedData bytes] encoding:NSUTF8StringEncoding];
	 
	[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
}
- (void)vpnLoginFailed
{
    NSLog(@"vpnLoginFailed");
}
- (void)vpnLoginFinished
{
    NSLog(@"vpnLoginFinished");
}
- (void)loadWebPageWithString:(NSString*)urlString
{
    NSURL *url = [NSURL URLWithString:urlString];
//    NSURL *url = [NSURL URLWithString:@"http://www.baidu.com/s?tn=baiduhome_pg&bs=%B9%AB%D3%C3%B7%FE%CE%F1%C6%F7%BD%D3%BF%DA%B2%E2%CA%D4iphone+%B3%CC%D0%F2&f=8&rsv_bp=1&rsv_spt=1&wd=ipad+&inputT=4013"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [webView loadRequest:request];
}
- (void)webViewDidStartLoad:(UIWebView *)webView
{
    [activityIndicatorView startAnimating] ;
}
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    [activityIndicatorView stopAnimating];
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
    UIAlertView *alterview = [[UIAlertView alloc] initWithTitle:@"" message:[error localizedDescription]  delegate:nil cancelButtonTitle:nil otherButtonTitles:@"i know", nil];
    [alterview show];
    [alterview release];
}
- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
	[super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
	[super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

@end
